<?php
/**
 * （Logic）解析转款报告-SettlementDeposit
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\SalesReport\FBADeposit;
use App\Util\RExcel;
class ParseDepositReport
{
    /**
     * 解析SettlementDeposit
     * @param $file
     * @param $account
     * @param $reportLoadId
     * @return int
     */
    public static function exeParse($file,$account,$reportLoadId){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        $lines = RExcel::importFile($file);
        $i = 0;
        $count = 0;
        $headAdd = [];
        $headUp = [];
        try{
            foreach($lines as $_str){
                $str = ParseReport::getReplaceStr($_str);
                if($i == 0){
                    $headAdd = ParseReport::getTableHeadKey($str,self::$_keysAdd);
                    $headUp = ParseReport::getTableHeadKey($str,self::$_keysUp);
                    if(empty($headAdd) || empty($headUp))return 2;
                }elseif($i == 1){
                    $flag = self::_addSettlementDeposit($account->id,$headAdd,$str,$reportLoadId);
                    $flag && $count++;
                }else{
                    $flag = self::_upSettlementDeposit($headUp,$str);
                    $flag && $count++;
                }
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i==($count+1) ? 2 : 3;
    }

    private static $_keysAdd = ['settlement-id',
        'settlement-start-date',
        'settlement-end-date',
        'deposit-date',
        'total-amount',
        'currency'];

    private static $_keysUp = ['settlement-id',
        'marketplace-name',
        'amount-description',
        'amount'];

    private static $_match = [
        'Previous Reserve Amount Balance' => 'pre_reserve_amount_balance',
        'Current Reserve Amount' => 'cur_reserve_amount'];

    private static function replaceAmount($subject) {
        return floatval(str_replace(',','.',$subject));
    }

    /**
     * 添加SettlementDeposit
     * @param $accountId
     * @param $head
     * @param $str
     * @param $reportLoadId
     * @return bool
     */
    private static function _addSettlementDeposit($accountId,$head,$str,$reportLoadId){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keysAdd;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        if(!$temp[$head['settlement-id']])return true;
        $count = FBADeposit::query()->where('settlement_id',$temp[$head['settlement-id']])->count();
        if($count > 0)return true;
        $currency = strtoupper($temp[$head['currency']]);
        if($currency == 'EUR'){
            $countryId = FBADeposit::$_EURCountryId;
            $areaId = SysArea::getSysAreaIdByArea('EU');
        }else{
            $countryId = AmazonCountry::getCountryIdByCurrencyCode($currency);
            $countryId = $countryId ?: 0;
            $areaId = SysICountry::getAreaIdByCountryId($countryId);
        }

        //转款报告
        $depositDate = gmdate('Y-m-d H:i:s',strtotime($temp[$head['deposit-date']]));
        $re = FBADeposit::query()->create([
            'settlement_id' => $temp[$head['settlement-id']],
            'account_id' => $accountId,
            'area_id' => $areaId,
            'country_id' => $countryId,
            'report_load_id' => $reportLoadId,
            'settlement_sdate' => gmdate('Y-m-d H:i:s',strtotime($temp[$head['settlement-start-date']])),
            'settlement_edate' => gmdate('Y-m-d H:i:s',strtotime($temp[$head['settlement-end-date']])),
            'deposit_date' => $depositDate,
            'total_amount' => self::replaceAmount($temp[$head['total-amount']]),
            'currency' => $currency,
            'rate_odds' => ExchangeRate::getRateOddsToRMB($currency,strtotime($depositDate)),
        ]);
        return !$re ? false : true;
    }

    /**
     * 更新SettlementDeposit
     * @param $head
     * @param $str
     * @return bool
     */
    private static function _upSettlementDeposit($head,$str){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keysUp;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        if(!$temp[$head['settlement-id']])return true;
        $re = FBADeposit::query()->where('settlement_id',$temp[$head['settlement-id']])->first();
        if(!$re)return true;
        if(!array_key_exists($temp[$head['amount-description']],self::$_match)){
            if($re->country_id == 99){
                $countryId = FBADeposit::getEUCountryId($temp[$head['marketplace-name']]);
                if($countryId){
                    $re->country_id = $countryId;
                    $reFlag = $re->save();
                    return !$reFlag ? false : true;
                }
            }
            return true;
        }else{
            if($re->country_id == 99){
                $countryId = FBADeposit::getEUCountryId($temp[$head['marketplace-name']]);
                if($countryId){
                    $re->country_id = $countryId;
                }
            }
            $re->{self::$_match[$temp[$head['amount-description']]]} = self::replaceAmount($temp[$head['amount']]);
            $reFlag = $re->save();
            return !$reFlag ? false : true;
        }
    }
}
